package com.ywk.pattern._21_singleton._21_4;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Constructor;

public class Main {
    static Singleton singleton = null;

    public static void main(String[] args) throws Exception {
        //通过反射破解单例模式
        Class clazz = Class.forName("com.ywk.pattern._21_singleton._21_4.Singleton");
        Constructor c = clazz.getDeclaredConstructor(null);
        c.setAccessible(true);
        Singleton s1 = (Singleton) c.newInstance();
        Singleton s2 = (Singleton) c.newInstance();
        System.out.println(s1 == s2);


        //通过反序列化破解单例模式
        Singleton s3 = Singleton.getInstance();
        Singleton s4 = Singleton.getInstance();
        FileOutputStream fos = new FileOutputStream("1.txt");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(s3);
        oos.close();
        fos.close();

        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("1.txt"));
        Singleton s5 = (Singleton) ois.readObject();
        System.out.println(s3 == s4);
        System.out.println(s4 == s5);




        for (int i = 0; i < 5; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Singleton instance = Singleton.getInstance();
                    if (singleton == null) {
                        singleton = instance;
                    }
                    System.out.println(singleton == instance);
                    singleton = instance;

                }
            }).start();
        }
    }
}
